import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image, TextInput, ScrollView,
	Alert, Platform, Keyboard, Modal, DatePickerIOS, DatePickerAndroid
} from 'react-native';
import { Geolocation } from 'react-native-baidu-map';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { cStyles } from '../RequirementStyle.js'
import { InputRow, LargeBtn } from '../component/Component.js';
import { Common } from '../../../component/common/Common';

const scale = GLOBAL.SCALE;
const arrowLeft = require('../../../imgs/arrow-left.png');
let sendData = {}
let addressObj = {
}

export class LogisticalPage extends Component {

	static navigationOptions = ({ navigation }) => {
		const params = navigation.state.params || {};
		const { addressCodeParam } = params;
		if (addressCodeParam) {
			addressObj = addressCodeParam;
			if (!addressObj.name) {
				addressObj.name = addressObj.poiInfo;
			}

			if (params.setAddress) {
				params.setAddress(addressObj);
			}
		}
		return {
			headerTitle: '物流',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		}
	};

	constructor(props) {
		super(props);
		this.curDateId = 'beginDate';
		let beginDateStr = '请选择';
		let endDateStr = '请选择';
		sendData = {};
		if (this.props.navigation.state.params.logistical) {
			sendData = this.props.navigation.state.params.logistical;
			if (sendData) {
				const { deliveryBeginDate, deliveryEndDate, addressData } = sendData;
				if (deliveryBeginDate) {
					beginDateStr = this._getDateStr(deliveryBeginDate);
				}
				if (deliveryEndDate) {
					endDateStr = this._getDateStr(deliveryEndDate);
				}
				if (addressData) {
					addressObj = addressData;
				} else {
					this.getCurrentPosition();
				}
			}
		} else {
			this.getCurrentPosition();
		}

		this.state = {
			detailAddress: '请选择',
			dateModalVisible: false,
			pickerDate: new Date(),
			beginDateStr,
			endDateStr,
			minDate: null,
			maxDate: null,
		}
		this._closeDateModal = this._closeDateModal.bind(this);
		this._getBeginDateView = this._getBeginDateView.bind(this);
		this._getEndDateView = this._getEndDateView.bind(this);
		this.setAddress = this.setAddress.bind(this);
	}

	componentWillMount () {
		this.props.navigation.setParams({
			setAddress: this.setAddress,
		});
		this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
		this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
	}

	componentWillUnmount () {
		try {
			this.keyboardDidShowListener.remove();
			this.keyboardDidHideListener.remove();
		} catch (error) {
			console.log(error);
		}
	}

	_keyboardDidShow () {
		this.setState({ keyboard: true });
	}

	_keyboardDidHide () {
		this.setState({ keyboard: false });
	}

	render () {
		const { detailAddress, keyboard, dateModalVisible, pickerDate, minDate, maxDate } = this.state;
		const beginDateView = this._getBeginDateView();
		const endDateView = this._getEndDateView();
		let keyboardStyle = null;
		if (Platform.OS === 'android') {
			if (keyboard) {
				keyboardStyle = { top: -50 * scale, };
			}
		}
		return (
			<View style={styles.container} >
				{/* <ScrollView style={[styles.scrollView, keyboardStyle]} keyboardShouldPersistTaps={'never'} keyboardDismissMode={'on-drag'}> */}
				<ScrollView style={[styles.scrollView, keyboardStyle]} >
					<View style={{ backgroundColor: '#fff', alignItems: 'center', }}>
						<View style={styles.wrap}>
							<InputRow text={'提货开始时间'}>{beginDateView}</InputRow>
							<InputRow text={'提货结束时间'}>{endDateView}</InputRow>
							<InputRow text={'数量'}>
								<View style={styles.inputRowRight}>
									<TextInput
										ref="quantityInput"
										style={cStyles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入"}
										placeholderTextColor="#999"
										maxLength={30}
										editable={true}
										defaultValue={sendData.quantity}
										keyboardType="numeric"
										onChangeText={(txt) => { sendData.quantity = txt; }}
									/></View>
							</InputRow>
							{/*<InputRow text={'出库地点'}>
								<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', flexWrap: 'nowrap', }]} onPress={() => {
									const { navigate } = this.props.navigation;
									navigate('AddressOptionPage', {
										addressObj,
										goBackPage: 'LogisticalPage'
									});
								}} activeOpacity={0.5} >
									<Text style={cStyles.text} numberOfLines={1}>{sendData.address || '请选择'}</Text>
									<Image source={arrowLeft} style={styles.arrowLeft} />
								</TouchableOpacity>
							</InputRow>
							<InputRow text={'详细地址'}>
								<View style={styles.inputRowRight}>
									<TextInput
										style={cStyles.textInput}
										underlineColorAndroid='transparent'
										placeholder={"请输入"}
										placeholderTextColor="#999"
										maxLength={30}
										editable={true}
										defaultValue={sendData.addressStr}
										onChangeText={(txt) => { sendData.addressStr = txt; }}
									/></View>
							</InputRow>*/}
						</View>
					</View>
				</ScrollView>
				<LargeBtn onPress={() => {
					const { navigate } = this.props.navigation;
					const { quantity } = sendData;
					if (!(/^\d*\.?\d+$/).test(quantity)) {
						Alert.alert('请填写纯数字');
						this.refs.quantityInput.focus();
					} else {

						navigate('RequirementAdd', {
							logistical: sendData,
							ifNullParams: false
						});
					}

				}} text={'保存'} />

				<Modal animationType={"fade"}
					transparent={true}
					visible={dateModalVisible}
					onRequestClose={() => { }} >
					<View style={styles.containerModal}>
						<View style={styles.datePickerCell}>
							<View style={styles.datePickerHead}>
								<TouchableOpacity onPress={
									() => {
										this.setState({ dateModalVisible: false })
									}} activeOpacity={0.5}>
									<Text style={styles.datePickerHeadText}>取消</Text>
								</TouchableOpacity>
								<Text style={[styles.datePickerHeadText, { fontSize: 18 * scale, color: '#404040' }]}>请选择</Text>
								<TouchableOpacity onPress={this._closeDateModal} activeOpacity={0.5}><Text style={styles.datePickerHeadText}>确定</Text></TouchableOpacity>
							</View>
							<DatePickerIOS
								date={pickerDate}
								mode="date"
								onDateChange={(pickerDate) => {
									this.setState({ pickerDate });
								}}
								minimumDate={minDate}
								maximumDate={maxDate}
							/>
						</View>
					</View>
				</Modal>

			</View>
		);
	}

	setAddress (addressObj) {

		let { address, name } = addressObj;

		if (!name) {
			name = '';
		}

		const detailAddress = address + ' ' + name;
		this.setState({
			detailAddress
		});
		sendData.address = detailAddress;
		sendData.addressData = addressObj;
	}
	//for 时间格式
	_getDateStr (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "年" + (m < 10 ? "0" + m : m) + "月" + (d < 10 ? "0" + d : d) + "日";
			return dateStr;
		} else {
			return '';
		}
	}

	//关闭时间选择Modal for ios
	_closeDateModal () {
		const { pickerDate } = this.state;
		const dateStr = this._getDateStr(pickerDate);
		if (this.curDateId == 'beginDate') {
			sendData.deliveryBeginDate = pickerDate;
			this.setState({
				beginDateStr: dateStr,
				minDate: pickerDate
			});
		} else {
			sendData.deliveryEndDate = pickerDate;
			this.setState({
				endDateStr: dateStr,
				maxDate: pickerDate
			});
		}

		this.setState({
			dateModalVisible: false
		});

	}

	//for 提货开始时间
	_getBeginDateView () {
		const { beginDateStr, maxDate } = this.state;
		console.log('beginDateStr:', beginDateStr);
		console.log('maxDate:', maxDate);
		if (Platform.OS == "ios") {
			return (
				<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => {
					this.curDateId = 'beginDate';
					const pickerDate = sendData.deliveryBeginDate ? sendData.deliveryBeginDate : new Date();
					this.setState({
						dateModalVisible: true,
						minDate: null,
						pickerDate
					});
				}} activeOpacity={0.5} >
					<Text style={cStyles.text}>{beginDateStr}</Text>
					<Image source={arrowLeft} style={styles.arrowLeft} />
				</TouchableOpacity>
			)
		} else {
			return (
				<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={async () => {
					const pickerDate = sendData.deliveryBeginDate ? new Date(sendData.deliveryBeginDate) : new Date();
					const dataInfo = {
						date: pickerDate,
						minDate: new Date()
					}
					if (maxDate) {
						dataInfo.maxDate = maxDate;
					}

					try {
						const { action, year, month, day } = await DatePickerAndroid.open(dataInfo);
						if (action !== DatePickerAndroid.dismissedAction) {
							const dataStr = year + "-" + (month < 10 ? "0" + (month + 1) : (month + 1)) + "-" + (day < 10 ? "0" + day : day);
							const beginDateStr = year + "年" + (month < 10 ? "0" + month : month) + "月" + (day < 10 ? "0" + day : day) + "日";

							sendData.deliveryBeginDate = new Date(year, month, day),
								// sendData.deliveryBeginDate = dataStr;
								this.setState({
									beginDateStr: dataStr,
									minDate: new Date(year, month, (day + 1)),
								});
						}
					} catch ({ code, message }) {
						console.warn('Cannot open date picker', message);
					}
				}} activeOpacity={0.5} >
					<Text style={cStyles.text}>{beginDateStr}</Text>
					<Image source={arrowLeft} style={styles.arrowLeft} />
				</TouchableOpacity>
			)
		}
	}

	//for 提货结束时间
	_getEndDateView () {
		const { endDateStr, minDate } = this.state;
		if (Platform.OS == "ios") {
			return (
				<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={() => {
					this.curDateId = 'endDate';
					const pickerDate = sendData.deliveryEndDate ? sendData.deliveryEndDate : new Date();
					this.setState({
						dateModalVisible: true,
						maxDate: null,
						pickerDate
					});
				}} activeOpacity={0.5} >
					<Text style={cStyles.text}>{endDateStr}</Text>
					<Image source={arrowLeft} style={styles.arrowLeft} />
				</TouchableOpacity>
			)
		} else {
			return (
				<TouchableOpacity style={[styles.inputRowRight, { justifyContent: 'space-between', }]} onPress={async () => {
					const pickerDate = sendData.deliveryEndDate ? new Date(sendData.deliveryEndDate) : new Date();
					const dataInfo = {
						date: pickerDate,
					}
					if (minDate) {
						dataInfo.minDate = minDate;
					}
					try {
						const { action, year, month, day } = await DatePickerAndroid.open(dataInfo);
						if (action !== DatePickerAndroid.dismissedAction) {
							const dataStr = year + "-" + (month < 10 ? "0" + (month + 1) : (month + 1)) + "-" + (day < 10 ? "0" + day : day);
							const endDateStr = year + "年" + (month < 10 ? "0" + month : month) + "月" + (day < 10 ? "0" + day : day) + "日";

							sendData.deliveryEndDate = new Date(year, month, day),
								// sendData.deliveryEndDate = dataStr;
								this.setState({
									endDateStr: dataStr,
									maxDate: new Date(year, month, (day + 1)),
								});
						}
					} catch ({ code, message }) {
						console.warn('Cannot open date picker', message);
					}
				}} activeOpacity={0.5} >
					<Text style={cStyles.text}>{endDateStr}</Text>
					<Image source={arrowLeft} style={styles.arrowLeft} />
				</TouchableOpacity>
			)
		}
	}

	//获取地理位置
	getCurrentPosition () {
		Geolocation.getCurrentPosition().then(
			(data) => {
				const { province, city, district, address } = data;
				this.setState({
					detailAddress: address
				});
				sendData.address = address;

				addressObj = data;

				if (!addressObj.name) {
					addressObj.name = addressObj.poiInfo;
				}
				console.log(addressObj);
			}
		).catch(error => {
			console.warn(error, 'error')
		})
	}
}

const styles = StyleSheet.create({
	containerModal: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		justifyContent: 'flex-end'
	},
	datePickerCell: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: '50%',
	},
	datePickerHead: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 40 * scale,
		width: 375 * scale,
	},
	datePickerHeadText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
		paddingTop: 16 * scale,
	},
	scrollView: {
		// flex: 1,
		paddingTop: 12 * scale,
		backgroundColor: '#F6F6F6',
	},
	container: {
		flex: 1,
	},
	wrap: {
		width: 345 * scale,
	},
	arrowLeft: {
		width: 6 * scale,
		height: 11 * scale,
	},
	inputRowRight: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
	},
})